package com.zkzx.operation.api.config;

import com.zkzx.common.exception.BaseException;
import com.zkzx.common.exception.ErrorEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author young Email:yanghui@zkraising.com
 * @description
 * @company 北京中科智兴物联科技有限公司 @版权所有
 * @since 2021年05月06日 17时32分
 */
@RestControllerAdvice(basePackages = {"com.zkzx"})
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class OperationApiExceptionTranslator {

    /**
     * Exception 异常连接  所有异常
     * @param ex 异常信息
     * @return 异常信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorEntity processBaseException(Exception ex) {
        log.error("服务器异常信息：{}",ex.getMessage());
        return  new ErrorEntity(HttpStatus.INTERNAL_SERVER_ERROR.value(),
              Objects.isNull(ex.getMessage())? "服务器错误" : ex.getMessage());
    }

    /**
     * BaseException 自定义异常拦截
     * @param ex 异常信息
     * @return 异常信息
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorEntity processBaseException(BaseException ex) {
        log.error("服务器异常信息：{},{}",ex.getErrCode(),ex.getErrMsg());
        return new ErrorEntity(ex.getErrCode(), ex.getErrMsg());
    }

}
